package com.fingard.dsp.bank.directbank.dlcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;

/**
 * 大连银行银行明细查询
 * <p>
 * 参考文档：大连银行银企直联企业对接交易接口(部分)v1.0.2.docx
 *
 * @author Cruise
 * @date 2018/11/06
 */
public class DLCB01Transaction extends DLCB01Base implements ITransaction {
    /**
     * 历史明细查询
     * <p>
     * 支持接口：2.1.3	账户交易明细查询 �C416B200110A(核心取明细)
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            // 按天查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                // 判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    // 跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                DLCB01Header tmpBankHeader = new DLCB01Header();
                tmpBankHeader.trncode = "416B200110A";
                tmpBankHeader.reqSeqNo = p_req7516.reqHeader.transSeqID;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeader(xmlWriter, tmpBankHeader);

                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("acno", p_req7516.actNum);
                xmlWriter.writeElementString("cms_corp_no", bankFront.corpNo);
                xmlWriter.writeElementString("cur_code", "01");
                xmlWriter.writeElementString("start_date", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("end_date", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                xmlWriter.writeElementString("reserved2", "");
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//                String[] tmpStrRet = new String[]{"", ""};
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if ("0".equals(tmpSuccFlag) && "0000".equals(tmpRetCode)) {
                            tmpRespCode = "0";
                            String recordNum = tmpBkReader.getFirstText("/ap/body/total");
                            if ("0".equals(recordNum)) {
                                if (!retAts.hasWrittenRespCode) {
                                    retAts.writeRespCode("0");
                                }
                                if (!retAts.hasWrittenRespInfo) {
                                    retAts.writeRespInfo("查询条件无记录。");
                                }
                                retAts.writeEnd();
                                return retAts;
                            }
                            String tmpResultStr = "";
                            if (StringHelper.hasAnyChar(tmpBkReader.getFirstText("/ap/body/serial_record"))) {
                                tmpResultStr = tmpBkReader.getFirstText("/ap/body/serial_record");
                                WriteBankLogLn2("当日明细文件内容:\r\n" + tmpResultStr);

                                String[] tmpTotalArray = tmpResultStr.split("\\|");

                                int tmpTotalArrayLen = tmpTotalArray.length;
                                for (int i = 1; i < tmpTotalArrayLen / 46; i++) {
                                    int baseNum = 46 * i;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actNum = tmpTotalArray[1 + baseNum];
                                    tmpRetDetail.tranDate = DateHelper.getFormat12Date(tmpTotalArray[3 + baseNum]);// 格式yyyy-MM-dd
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + DateHelper.getFormat8Time(tmpTotalArray[4 + baseNum]);// 格式"yyyy-MM-dd HH:mm:ss"
                                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    tmpRetDetail.tranAmt = tmpTotalArray[25 + baseNum];
                                    tmpRetDetail.accBal = tmpTotalArray[26 + baseNum];
                                    tmpRetDetail.cdFlag = "D".equals(tmpTotalArray[24 + baseNum]) ? ("1") : ("2");
                                    tmpRetDetail.recAccNum = tmpTotalArray[9 + baseNum];
                                    tmpRetDetail.recAccName = tmpTotalArray[11 + baseNum];
                                    tmpRetDetail.recAccBank = tmpTotalArray[12 + baseNum];
                                    tmpRetDetail.usage = tmpTotalArray[35 + baseNum];
                                    String postScript = tmpTotalArray[36 + baseNum];
                                    tmpRetDetail.comment = postScript;
                                    tmpRetDetail.abstr = postScript;
                                    if (postScript.contains("-")) {
                                        tmpRetDetail.abstr = postScript.substring(0, postScript.indexOf("-"));
                                    }
                                    tmpRetDetail.payCode = tmpTotalArray[34 + baseNum];
                                    tmpRetDetail.cur = "1";
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                String tmpDetailFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                tmpResultStr = FileHelper.readFileText(StringHelper.trimEnd(bankFront.folderForRemoteHost, File.separator) + File.separator + tmpDetailFileName, getCharset());
                                WriteBankLogLn2("当日明细文件内容:\r\n" + tmpResultStr);

                                StringReader strReader = new StringReader(tmpResultStr);
                                BufferedReader tmpReader = new BufferedReader(strReader);
                                tmpReader.readLine();

                                while (true) {
                                    String eachline = tmpReader.readLine();
                                    if (eachline == null) {
                                        break;
                                    }
                                    if (eachline.contains("|")) {
                                        String[] bodyValues = eachline.split("\\|");
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        //  0平台流水号（C20）|1账号（C35）|2货币码（C2）|3交易日期（C8）|4交易时间|5交易日期（C6）|
                                        //  6主机流水号（C20）|7交易行号(C12)|8户名(C70)|9对方账号(C35)|10对方货币码(C2)|11对方账号户名(C70)|
                                        //  12对方账号开户行(C60)|13对方行号(C12)|14交易类别(C1)|15钞汇标志(C1)|16他行标志(C1)|17同城异地标志(C1)|
                                        //  18手续费(N16.2)|19交易来源(C1)|20发生额标志(C1)|21被冲销流水号(C12)|22原交易日期(C8)|23现转标志(C1)|
                                        //  24借贷标志(C1)|25交易金额(N16.2)|26余额(N16.2)|27上笔余额(N16.2)|28冻结金额(N16.2)|29凭证种类(C20)|
                                        //  30凭证批次号(C20)|31凭证号码(C20)|32交易码(C6)|33柜员号(C10)|34传票号(C20)|35摘要(C30)|36附言(C60)|
                                        //  37交易时间戳|38备注字段一(C60)|39备注字段二(C60)| 40支付行名(C60)|41行号|42行名|43打印次数|44借入金额(N16,2)|
                                        //  45借出金额(N16,2)|
                                        tmpRetDetail.actNum = bodyValues[1];
                                        tmpRetDetail.tranDate = DateHelper.getFormat12Date(bodyValues[3]);// 格式yyyy-MM-dd
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + DateHelper.getFormat8Time(bodyValues[4]);// 格式"yyyy-MM-dd HH:mm:ss"
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                        tmpRetDetail.tranAmt = bodyValues[25];
                                        tmpRetDetail.accBal = bodyValues[26];
                                        tmpRetDetail.cdFlag = "D".equals(bodyValues[24]) ? ("1") : ("2");
                                        tmpRetDetail.recAccNum = bodyValues[9];
                                        tmpRetDetail.recAccName = bodyValues[11];
                                        tmpRetDetail.recAccBank = bodyValues[12];
                                        tmpRetDetail.usage = bodyValues[35];

                                        String postScript = bodyValues[36];
                                        tmpRetDetail.abstr = postScript;
                                        tmpRetDetail.comment = postScript;
                                        if (postScript.contains("-")) {
                                            tmpRetDetail.abstr = postScript.substring(0, postScript.indexOf("-"));
                                            tmpRetDetail.usage = postScript.substring(postScript.indexOf("-"));
                                        }
//                                        tmpRetDetail.abstr = bodyValues[36];
                                        tmpRetDetail.payCode = bodyValues[34];
                                        tmpRetDetail.cur = "1";

                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        retAts.writeEnd();
        return retAts;
    }

    /**
     * 今日明细查询
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);

        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;

        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;

        return d_7516_HisTrans(tmpReq7516);
    }
}
